package cn.tedu.tmall.admin.mall.service.impl;

import cn.tedu.tmall.admin.mall.dao.persist.repository.ICategoryRepository;
import cn.tedu.tmall.admin.mall.dao.persist.repository.IGoodRepository;
import cn.tedu.tmall.admin.mall.dao.persist.repository.IGoodsDetailRepository;
import cn.tedu.tmall.admin.mall.dao.persist.search.GoodsElasticSearchRepository;
import cn.tedu.tmall.admin.mall.pojo.entity.Goods;
import cn.tedu.tmall.admin.mall.pojo.entity.GoodsDetail;
import cn.tedu.tmall.admin.mall.pojo.param.GoodsAddNewParam;
import cn.tedu.tmall.admin.mall.pojo.param.GoodsUpdateInfoParam;
import cn.tedu.tmall.admin.mall.pojo.vo.CategoryStandardVO;
import cn.tedu.tmall.admin.mall.pojo.vo.GoodsListItemVO;
import cn.tedu.tmall.admin.mall.pojo.vo.GoodsStandardVO;
import cn.tedu.tmall.admin.mall.service.IGoodService;
import cn.tedu.tmall.common.enumerator.ServiceCode;
import cn.tedu.tmall.common.ex.ServiceException;
import cn.tedu.tmall.common.pojo.authentication.CurrentPrincipal;
import cn.tedu.tmall.common.pojo.po.GoodsSearchPO;
import cn.tedu.tmall.common.pojo.vo.PageData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class GoodServiceImpl implements IGoodService {
    @Value("${tmall.dao.default-query-page-size}")
    private Integer defaultQueryPageSize;
    @Autowired
    private IGoodRepository goodRepository;
    @Autowired
    private IGoodsDetailRepository goodsDetailRepository;
    @Autowired
    private ICategoryRepository categoryRepository;
    @Autowired
    private GoodsElasticSearchRepository searchRepository;
    @Override
    public void addNew(CurrentPrincipal currentPrincipal, GoodsAddNewParam goodsAddNewParam) {
        Long categoryId = goodsAddNewParam.getCategoryId();
        CategoryStandardVO categoryStandardVO = categoryRepository.getStandardById(categoryId);
        if(categoryStandardVO==null){
            String message = "发布商品失败，该类别不存在";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        if(categoryStandardVO.getIsParent()!=0){
            String message = "发布商品失败，选择的类别不应包含子级";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
        }
        if(categoryStandardVO.getEnable()==0){
            String message = "发布商品失败，该类别已被禁用";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
        }
        Goods good = new Goods();
        BeanUtils.copyProperties(goodsAddNewParam,good);
        good.setCategoryName(categoryStandardVO.getName());
        good.setIsRecommend(RECOMMEND_STATE_OFF);
        good.setCheckState(CHECK_STATE_UNCHECKED);
        good.setIsPutOn(PUT_ON_STATE_OFF);
        good.setSalesCount(0);
        good.setCommentCount(0);
        good.setPositiveCommentCount(0);
        good.setNegativeCommentCount(0);
        int rows = goodRepository.insert(good);
        if (rows != 1) {
            String message = "发布商品失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }

        GoodsDetail goodsDetail = new GoodsDetail();
        goodsDetail.setGoodsId(good.getId());
        goodsDetail.setDetail(goodsAddNewParam.getDetail());
        rows = goodsDetailRepository.insert(goodsDetail);
        if (rows != 1) {
            String message = "发布商品失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_INSERT, message);
        }
    }

    @Override
    public void delete(Long id) {
        //TODO 1.判断该商品是否存在
        //TODO 2.删除关联信息
        GoodsStandardVO goodsStandardVO = goodRepository.selectById(id);
        if(goodsStandardVO==null){
            String message = "删除失败，该商品不存在";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        int rows= goodRepository.deleteById(id);
        if (rows != 1) {
            String message = "删除失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }
        rows = goodsDetailRepository.deleteByGoodId(id);
        if (rows != 1) {
            String message = "删除失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERROR_DELETE, message);
        }
    }

    @Override
    public void updateById(Long id, GoodsUpdateInfoParam goodsUpdateInfoParam) {
        // TODO 1.判断该商品是否存在
        // TODO 2.判断该商品类别是否禁用
        GoodsStandardVO goodsStandardVO = goodRepository.selectById(id);
        if(goodsStandardVO==null){
            String message = "更新商品失败，该商品不存在";
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,message);
        }
        CategoryStandardVO categoryStandardVO = categoryRepository.getStandardById(goodsStandardVO.getCategoryId());
        if(categoryStandardVO.getEnable()!=1){
            String message = "更新商品失败，该类别已被禁用";
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,message);
        }
        //修改商品
        Goods goods = new Goods();
        BeanUtils.copyProperties(goodsUpdateInfoParam,goods);
        goods.setId(id);
        goods.setIsRecommend(RECOMMEND_STATE_OFF);
        goods.setCheckState(CHECK_STATE_UNCHECKED);
        goods.setIsPutOn(PUT_ON_STATE_OFF);
        goodRepository.updateById(goods);

        //修改商品详情
        GoodsDetail goodsDetail = new GoodsDetail();
        goodsDetail.setDetail(goodsUpdateInfoParam.getDetail());
        QueryWrapper<GoodsDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",id);
        goodsDetailRepository.update(goodsDetail,queryWrapper);
    }

    @Override
    public GoodsStandardVO selectById(Long id) {
        GoodsStandardVO goodsStandardVO = goodRepository.selectById(id);
        return goodsStandardVO;
    }

    @Override
    public PageData<GoodsListItemVO> list(Integer pageNum) {
        PageData<GoodsListItemVO> pageData =
                goodRepository.list(pageNum, defaultQueryPageSize);
        return pageData;
    }

    @Override
    public PageData<GoodsListItemVO> list(Integer pageNum, Integer pageSize) {
        PageData<GoodsListItemVO> pageData =
                goodRepository.list(pageNum, pageSize);
        return pageData;
    }

    @Override
    public PageData<GoodsListItemVO> listByCategoryId(Long categoryId, Integer pageNum) {
        PageData<GoodsListItemVO> pageData =
                goodRepository.listByCategoryId(categoryId, pageNum, defaultQueryPageSize);
        return pageData;
    }

    @Override
    public PageData<GoodsListItemVO> listByCategoryId(Long categoryId, Integer pageNum, Integer pageSize) {
        PageData<GoodsListItemVO> pageData =
                goodRepository.listByCategoryId(categoryId, pageNum, pageSize);
        return pageData;
    }

    @Override
    public void rebuildSearch() {
        searchRepository.deleteAll();
        Integer pageNum = 1;
        Integer pageSize = 3;
        PageData<GoodsSearchPO> pageData;
        Integer maxPage;
        do {
            pageData = goodRepository.listSearch(pageNum, pageSize);
            maxPage = pageData.getMaxPage();
            searchRepository.saveAll(pageData.getList());
            pageNum++;
        }while (pageNum<=maxPage);
    }
}
